package cn.edu.seu.cose.qol.model.dao.database.util;

import java.util.Collection;
import java.util.LinkedList;

public class StringArraySerializer {
	
	private static String DIVIDING = "|";
	
	private static StringArraySerializer _instance;
	
	public static StringArraySerializer getInstance() {
		if (_instance == null) {
			_instance = new StringArraySerializer();
		}
		return _instance;
	}
	
	private static String escape(String s) {
		return s.replaceAll(DIVIDING, "\\" + DIVIDING);
	}
	
	private static String unescape(String s) {
		return s.replaceAll("\\" + DIVIDING, DIVIDING);
	}
	
	protected StringArraySerializer() {}
	
	public String serialize(Collection<String> strs) {
		StringBuilder builder = new StringBuilder();
		for (String s: strs) {
			String escaped = escape(s);
			builder.append(escaped);
			builder.append(DIVIDING);
		}
		return builder.toString();
	}
	
	public Collection<String> deserialize(String storedStr) {
		String[] strArray = storedStr.split(DIVIDING);
		LinkedList<String> collection = new LinkedList<String>();
		for (String s: strArray) {
			String unescaped = unescape(s);
			collection.add(unescaped);
		}
		return collection;
	}

}
